import Upload from './Upload'
import Table from './Table'
import List from './List'
import { downloadFile } from '@/api/common'
export default {
  install(Vue) {
    Vue.component(Table.name, Table)
    Vue.component(Upload.name, Upload)
    Vue.component(List.name, List)
    Object.defineProperty(Vue.prototype, '$getFiles', { value: function(fileList, modelId, filterData = false) {
      fileList = filterData ? fileList.filter(e => e.flag !== 'data') : fileList
      return fileList.map(file => {
        const data = { ...file.response.data }
        if (typeof modelId === 'string') {
          data.modelId = modelId
        } else if (typeof modelId === 'boolean' && modelId) {
          delete data.modelId
        }
        return data
      })
    } })
    function getUrl(url) {
      if (typeof url === 'object') {
        url = url.attachmentUrl.replace(/^\//, '')
      }
      if (/^https?:/.test(url)) {
        return url
      }
      let prefix = process.env.VUE_APP_IMG_PREFIX.replace(/(^\/)|(\/$)/g, '')
      prefix = /^https?:/.test(prefix) ? prefix : `${location.origin}/${prefix}`
      return prefix + '/' + url
    }
    Object.defineProperty(Vue.prototype, '$getUrl', { value: getUrl })
    Object.defineProperty(Vue.prototype, '$downFile', { value: function(file) {
      let fileName = file.attachmentName
      if (fileName.replace(/(.*)\.(\w+)$/g, '$2') !== file.typeName.replace(/\.(\w+)$/, '$1')) {
        fileName = `${fileName}.${file.typeName.replace('.', '')}`
      }
      return downloadFile(file.attachmentUrl).then(res => {
        const t = URL.createObjectURL(res)
        const a = document.createElement('a')
        a.href = t
        a.download = fileName
        a.click()
        setTimeout(() => {
          URL.revokeObjectURL(t)
        }, 30 * 1000)
      })
    } })
  }
}
